package com.qf.security;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  


import com.fasterxml.jackson.databind.ObjectMapper;

import com.qf.dto.R;
import com.qf.entity.MyAuthUser;
import com.qf.entity.TMenu;
import com.qf.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private MenuMapper menuMapper;


    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authentication);
        System.err.println("登录成功了");
        //获取当前登录成功的用户的权限
        Object principal = authentication.getPrincipal();
        System.err.println(principal);
        Long userId = ((MyAuthUser) principal).getId();//获取到当前登录的用户的 id
        //获取到当前用户的所有的权限
        //根据用户 id 获取到所有的角色的 id

        //根据角色的 id 获取到所有的地址的 id

        //根据 地址的 id 获取到所有的地址的信息
        List<TMenu> menuList = menuMapper.findAllMenusByUserId(userId);
//        Collection authorities = authentication.getAuthorities();//获取到用户的权限的集合,注意这个集合不可以修改
//        authorities.add(new SimpleGrantedAuthority("DASDASD"));
//        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        for (TMenu menu : menuList) {
//            String perms = menu.getPerms();
//            if (!ObjectUtils.isEmpty(perms)) {
//                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(perms);
//                grantedAuthorities.add(grantedAuthority);
//            }
//        }
        List<SimpleGrantedAuthority> authorityList = menuList.stream()
                .filter(menu -> !ObjectUtils.isEmpty(menu.getPerms()))//我们只保留有权限的数据
                .map(TMenu::getPerms)//将当前集合中符合我们要求的数据通过 getPerms转成字符串集合
                .map(SimpleGrantedAuthority::new)//将字符串集合遍历通过new SimpleGrantedAuthority将权限设置进去转换为权限对象
                .collect(Collectors.toList());
        //重新设置认证的相关信息
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), authorityList));

        R r = R.setOk();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(r));

    }
}
